<template>
  <div class="pages informationadd">
    <div class="pageLevel">
      <!-- 表单 -->
      <div class="from_main from">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
           <el-form-item class="fotter_button">
             <el-button type="primary" size="small" @click="goback()">返 回</el-button>
             <el-button type="primary" size="small" @click="submitForm('ruleForm')">发 布</el-button>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input onkeyup="this.value=this.value.replace(/^ +| +$/g,'')" placeholder="请输入标题" clearable v-model="ruleForm.title" maxlength="50" minlength="20" size="small"></el-input>
          </el-form-item>
          <el-form-item v-if="listconter" label="列表内容" prop="listcontent">
            <textarea onkeyup="this.value=this.value.replace(/^ +| +$/g,'')" v-model="ruleForm.listcontent" placeholder="请输入列表内容" name="" id="" cols="10" rows="5" maxlength="120" style="width:450px;resize:none">
          </textarea>
          </el-form-item>
          <el-form-item label="所属分类" prop="classifications">
            <el-radio-group v-model="ruleForm.classifications">
              <el-radio label="0">婴儿游泳</el-radio>
              <el-radio label="1">产后护理</el-radio>
              <el-radio label="2">儿童推拿</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="选择类别" prop="classification">
            <el-radio-group v-model="ruleForm.classification" @change="changeclassification">
              <el-radio label="0">文章</el-radio>
              <el-radio label="1">视频</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 选择文章得内容 -->
          <div v-if="islist">
            <el-form-item label="选择列表排版样式" prop="list">
              <el-radio-group v-model="ruleForm.list" @change="changelist">
                <el-radio label="0">标题内容</el-radio>
                <el-radio label="1">标题内容一张图片</el-radio>
                <el-radio label="2">标题内容三张图片</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 选择视频的内容 -->
          <div v-show="isvideo">
            <el-form-item label="封面" prop="dialogImageUrl2" ref="ageForm">
              <div class="block">
                <div class="imgbox"><img :src="ruleForm.dialogImageUrl2" @click="showimg(ruleForm.dialogImageUrl2)" alt=""></div>
                <el-upload :disabled="showtext" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                  <el-button :disabled="showtext" size="small" @click="addindex('dialogImageUrl2')" class="postionImg" type="primary">点击上传</el-button>
                </el-upload>
                <el-button class="postionAbsu"  size="small" @click="deleteImg('dialogImageUrl2')" type="primary">删除</el-button>
              </div>

            </el-form-item>
            <el-form-item label="视频连接地址" prop="videoaddress">
              <el-input onkeyup="this.value=this.value.replace(/^ +| +$/g,'')" id="input" v-model="ruleForm.videoaddress" size="small" placeholder="URI" clearable readonly> </el-input>
              <div class="videoadd">
                <input style="width: 70px !important;color:#fff;" accept="video/*" type="file" @change="tirggerFile($event)">
              </div>
            </el-form-item>

          </div>
          <!-- 图片得显示隐藏 -->
          <div v-show="islisttimg">
            <el-form-item label="封面" prop="dialogImageUrl" ref="ageForm">
              <div class="block">
                <div class="imgbox"><img :src="ruleForm.dialogImageUrl" @click="showimg(ruleForm.dialogImageUrl)" alt=""></div>
                <el-upload :disabled="showtext" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                  <el-button class="postionImg" :disabled="showtext" size="small" @click="addindex('dialogImageUrl')" type="primary">点击上传</el-button>

                </el-upload>
              </div>
              <el-button class="postionAbsu" style="margin-left:-102px;" size="small" @click="deleteImg('dialogImageUrl')" type="primary">删除</el-button>

            </el-form-item>
          </div>
          <div v-show="islisttimgs">
            <el-form-item label="封面" prop="" ref="ageForm">
              <div class="block">
                <div class="imgbox imgbox1"><img :src="ruleForm.dialogImageUrl3" @click="showimg( ruleForm.dialogImageUrl3)" alt=""></div>
                <el-upload :disabled="showtext" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                  <el-button class="postionImg postionImg1" :disabled="showtext" size="small" @click="addindex('dialogImageUrl3')" type="primary">点击上传</el-button>
                </el-upload>
                <el-button class="postionAbsu1" size="small" @click="deleteImg('dialogImageUrl3')" type="primary">删除</el-button>
              </div>

              <div class="block">
                <div class="imgbox"><img :src="ruleForm.dialogImageUrl4" @click="showimg(ruleForm.dialogImageUrl4)" alt=""></div>
                <el-upload :disabled="showtext" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                  <el-button class="postionImg postionImg2" :disabled="showtext" size="small" @click="addindex('dialogImageUrl4')" type="primary">点击上传</el-button>
                </el-upload>
                <el-button class="postionAbsu2" size="small" @click="deleteImg('dialogImageUrl4')" type="primary">删除</el-button>

              </div>
              <div class="block">
                <div class="imgbox"><img :src="ruleForm.dialogImageUrl5" @click="showimg(ruleForm.dialogImageUrl5)" alt=""></div>
                <el-upload :disabled="showtext" class="upload-demo" action="1" :show-file-list="false" :before-upload="beforeAvatarUpload" :http-request="uploadSectionFile">
                  <el-button :disabled="showtext" size="small" @click="addindex('dialogImageUrl5')" class="postionImg postionImg3" type="primary">点击上传</el-button>
                </el-upload>
                <el-button class="postionAbsu3" size="small" @click="deleteImg('dialogImageUrl5')" type="primary">删除</el-button>

              </div>

            </el-form-item>
          </div>
          <!-- 编辑器得显示隐藏 -->
          <div v-show="islisttitle">
            <el-form-item label="内容" prop="lists">
              <div id="editorElem" style="width: 550px;max-height:500px;"></div>
            </el-form-item>
          </div>

         
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
var htmlTop =
  '<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><meta name="viewport" content="width=device-width, initial-scale=1">' +
  '<style type="text/css">table {border-top: 1px solid #ccc;border-left: 1px solid #ccc;}' +
  "body{margin:0;padding:15px 15px 15px 15px;background-color:#fff;}" +
  "table td,table th {border-bottom: 1px solid #ccc;border-right: 1px solid #ccc;padding: 3px 5px;}" +
  "table th {border-bottom: 2px solid #ccc;text-align: center;}" +
  "h3{color:#333;font-size:18px;}" +
  "h1{color:#333;font-size:18px;}" +
  "h2{color:#333;font-size:18px;}" +
  "h4{color:#333;font-size:18px;}" +
  "h5{color:#333;font-size:18px;}" +
  "p{color:#666;line-height:30px;}" +
  "span{color:#999;font-size:14px;}" +
  "blockquote {display: block;border-left: 8px solid #d0e5f2;padding: 5px 10px;margin: 10px 0;line-height: 1.4;font-size: 100%;background-color: #f1f1f1;}" +
  "code {display: inline-block;*display: inline;*zoom: 1;background-color: #f1f1f1;border-radius: 3px;padding: 3px 5px;margin: 0 3px}" +
  "pre code {display: block;}ul, ol {margin: 10px 0 10px 20px;}img{width: 100%;}</style></head><body>";
var htmlfooter = "</body></html>";
import E from "wangeditor";
import { mapState } from "vuex";
import {
  uploadVideo,
  uploadFile,
  uploadHtml,
  saveOrUpdateMessage,
  getFile,
  uploadText,
  getvideoFile
} from "@/api";
export default {
  name: `clearFieldValidate`,
  computed: mapState(["merchantId"]),
  data() {
    return {
      showtext: false,
      imgindex: 0,
      jindu: "",
      listconter: true,
      ruleForm: {
        title: "",
        listcontent: "",
        classifications: "0",
        classification: "0",
        list: "0",
        //图片信息
        dialogImageUrl: "",
        dialogImageUrl3: "",
        dialogImageUrl4: "",
        dialogImageUrl5: "",
        dialogImageUrl1: [],
        dialogImageUrl2: "",
        videoaddress: "",
        videotime: ""
      },
      rules: {
        title: [
          { required: true, message: "请输入标题", trigger: "blur" },
          {
            min: 20,
            max: 50,
            message: "长度在 20 到 50 个字符",
            trigger: "blur"
          }
        ],
        classification: [
          { required: true, message: "请选择分类", trigger: "blur" }
        ],
        classifications: [
          { required: true, message: "请选择分类", trigger: "blur" }
        ],
        list: [
          {
            required: true,
            message: "请选择列表排版样式",
            trigger: "blur"
          }
        ],
        dialogImageUrl: [
          {
            required: false,
            message: "请选择一张封面",
            trigger: "blur"
          }
        ],
        dialogImageUrl1: [
          {
            required: false,
            message: "请选择三张封面",
            trigger: "blur"
          }
        ],
        videoaddress: [
          {
            required: false,
            message: "请输入视频连接地址",
            trigger: "blur"
          }
        ],
        videotime: [
          {
            required: false,
            message: "请输入视频播放时长",
            trigger: "blur"
          }
        ],
        listcontent: [
          {
            required: true,
            message: "请输入列表内容",
            trigger: "blur"
          }
        ]
      },
      // 排版列表得显示
      islist: true,
      // 选择标题和内容
      islisttitle: true,
      // 图片得显示隐藏
      islisttimg: false,
      islisttimgs: false,
      dialogVisible: false,
      dialogVisible1: false,
      // 编辑器
      editorContent: "",
      // 视频的显示隐藏
      isvideo: false
    };
  },
  mounted() {
    this.edit();
  },
  methods: {
    // 图片上传
    addindex(i) {
      this.imgindex = i;
    },
    deleteImg(i) {
      switch (i) {
        case "dialogImageUrl":
          this.ruleForm.dialogImageUrl = "";
          break;

        case "dialogImageUrl3":
          this.ruleForm.dialogImageUrl3 = "";
          break;

        case "dialogImageUrl4":
          this.ruleForm.dialogImageUrl4 = "";
          break;

        case "dialogImageUrl5":
          this.ruleForm.dialogImageUrl5 = "";
          break;

        case "dialogImageUrl2":
          this.ruleForm.dialogImageUrl2 = "";
          break;

        default:
          break;
      }
    },
    // 选择视频
    tirggerFile: function(event) {
      var files = event.target.files;
      var data3 = new FormData();
      data3.append("file", files[0]);
      data3.append("projectName", files[0].name);
   
      // uploadVideo(data3).then(res => {
      //   this.ruleForm.videoaddress = res.data.showImg;
      // });
      
      uploadFile(data3).then(res => {
        if (res.code==200) {
          let data={
          id:res.data.id,
          returnUrlFlag:1
        }
          
        getvideoFile(data).then(res => {
          this.ruleForm.videoaddress=res
        })
        }
        
        // this.ruleForm.videoaddress = `${getFile}?id=${res.data.id}`;
      });
    },
    // 选择分类
    changeclassification(val) {
      if (val == "0") {
        this.islist = true;
        this.islisttitle = true;
        this.isvideo = false;
        this.listconter = true;
        if (this.ruleForm.list == "1") {
          this.islisttimg = true;
        }
        if (this.ruleForm.list == "2") {
          this.islisttimgs = true;
        }
      } else if (val == "1") {
        this.islist = false;
        this.islisttitle = false;
        this.isvideo = true;
        this.listconter = false;
        this.islisttimg = false;
        this.islisttimgs = false;
      }
    },
    // 选择列表排版样式
    changelist(value) {
      if (value == "0") {
        this.islisttitle = true;
        this.islisttimg = false;
        this.islisttimgs = false;
      } else if (value == "1") {
        this.islisttitle = true;
        this.islisttimg = true;
        this.islisttimgs = false;
      } else if (value == "2") {
        this.islisttitle = true;
        this.islisttimg = false;
        this.islisttimgs = true;
      }
    },
    // 发布
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.ruleForm.classification == 0 && this.ruleForm.list == 2) {
            if (
              this.ruleForm.dialogImageUrl3 != "" &&
              this.ruleForm.dialogImageUrl4 != "" &&
              this.ruleForm.dialogImageUrl5 != ""
            ) {
              this.getContent();
            } else {
              this.$message({
                type: "error",
                message: "请选择三张图片"
              });
            }
          } else if (
            this.ruleForm.classification == 0 &&
            this.ruleForm.list == 1
          ) {
            if (this.ruleForm.dialogImageUrl != "") {
              this.getContent();
            } else {
              this.$message({
                type: "error",
                message: "请选择一张图片"
              });
            }
          } else if (this.ruleForm.classification == 1) {
            if (
              this.ruleForm.dialogImageUrl2 != "" &&
              this.ruleForm.videoaddress != ""
            ) {
              this.getContent();
            } else {
              this.$message({
                type: "error",
                message: "请选择一张图片或者选择视频地址"
              });
            }
          } else {
            this.getContent();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    goback(){
     history.back();
     },
    // 视频的粘贴
    paste() {
      var Url = document.getElementById("input");
      Url.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
    },

    // 编辑器
    edit() {
      this.editor = new E("#editorElem");
      this.editor.customConfig.onchange = html => {
        this.editorContent = html;
      };
      this.editor.customConfig.zIndex = 100;
      this.editor.customConfig.menus = [
        "head", // 标题
        "bold", // 粗体
        "fontSize", // 字号
        "fontName", // 字体
        "italic", // 斜体
        "underline", // 下划线
        "strikeThrough", // 删除线
        "backColor", // 背景颜色
        "link", // 插入链接
        "list", // 列表
        "justify", // 对齐方式
        "quote", // 引用
        // 'emoticon',  // 表情
        "image", // 插入图片
        "table", // 表格
        // 'video',  // 插入视频
        "code" // 插入代码
        // "undo", // 撤销
        // "redo" // 重复
      ];
      this.editor.customConfig.customUploadImg = (files, insert) => {
        var data = new FormData();
        data.append("file", files[0], files[0].name);
        data.append("projectName", files[0].name);
        uploadFile(data).then(res => {
          // console.log(res)
          insert(`${getFile}?id=${res.data.id}`);
        });
      };
      this.editor.create();
    },
    getContent() {
      var htmlBody = this.editorContent;
      var htmldat = htmlTop + htmlBody + htmlfooter;
      var data = new FormData();
      data.append("text", htmldat);
      data.append("projectName", "666");
      uploadText(data).then(res => {
        this.urladvice = `${getFile}?id=${res.data.id}`;
        console.log(this.urladvice)
        let Data = new FormData();
        Data.append("title", this.ruleForm.title);
        Data.append("type", this.ruleForm.classification);
        Data.append("style", this.ruleForm.list);

        if (this.ruleForm.classification == "1") {
          let imgarr = [];
          imgarr.push(this.ruleForm.dialogImageUrl2);
          Data.append("imageUrl", imgarr);
        }
        if (this.ruleForm.list == "1") {
          let imgarr1 = [];
          imgarr1.push(this.ruleForm.dialogImageUrl);
          Data.append("imageUrl", imgarr1);
        } else if (this.ruleForm.list == "2") {
          let imgarr2 = [];
          imgarr2.push(this.ruleForm.dialogImageUrl3);
          imgarr2.push(this.ruleForm.dialogImageUrl4);
          imgarr2.push(this.ruleForm.dialogImageUrl5);
          Data.append("imageUrl", imgarr2);
        }
        Data.append("videoUrl", this.ruleForm.videoaddress);
        Data.append("duration", this.ruleForm.videotime);
        Data.append("contentUrl", this.urladvice);
        Data.append("content", htmlBody);
        Data.append("subTitle", this.ruleForm.listcontent);
        Data.append("orgId", this.merchantId);
        Data.append("classify", this.ruleForm.classifications);
        if (
          (this.ruleForm.classification == 0 && this.editor.txt.text() != "") ||
          (this.ruleForm.list == 0 && this.editor.txt.text() != "")
        ) {
          saveOrUpdateMessage(Data).then(res => {
            this.$message({
              type: "success",
              message: res.msg
            });
            history.back();
          });
        } else if (
          this.ruleForm.classification == 1 &&
          this.editor.txt.text() == ""
        ) {
          saveOrUpdateMessage(Data).then(res => {
            this.$message({
              type: "success",
              message: res.msg
            });
            history.back();
          });
        } else {
          this.$message({
            type: "error",
            message: "请输入内容"
          });
        }
      });
    },
    // 图片上传
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      const isLt2M = file.size / 1024 / 1024 < 1;
      // 限制图片的宽和高
      // const isSize = new Promise(function(resolve, reject) {
      //   let width =1448
      //   let height =877
      //   let _URL = window.URL || window.webkitURL
      //   let img = new Image()
      //   img.onload = function() {
      //     let valid = img.width == width && img.height == height
      //     valid ? resolve() : reject()
      //   }
      //   img.src = _URL.createObjectURL(file)
      // }).then(
      //   () => {
      //     return file
      //   },
      //   () => {
      //     this.$message.error('上传图片的宽度为150px;高度为 100px!')
      //     return Promise.reject()
      //   }
      // )

      if (!isJPG) {
        this.$message.error("上传图片格式错误!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }

      return isJPG && isLt2M;
    },

    uploadSectionFile(param) {
      var fileObj = param.file;
      var data2 = new FormData();
      data2.append("file", fileObj);
      data2.append("projectName", fileObj.name);
     
      uploadFile(data2).then(res => {
        switch (this.imgindex) {
          case "dialogImageUrl":
            this.ruleForm.dialogImageUrl = `${getFile}?id=${res.data.id}`;
            break;
          case "dialogImageUrl3":
            this.ruleForm.dialogImageUrl3 = `${getFile}?id=${res.data.id}`;
            break;
          case "dialogImageUrl4":
            this.ruleForm.dialogImageUrl4 = `${getFile}?id=${res.data.id}`;
            break;
          case "dialogImageUrl5":
            this.ruleForm.dialogImageUrl5 = `${getFile}?id=${res.data.id}`;
            break;
          case "dialogImageUrl2":
            this.ruleForm.dialogImageUrl2 = `${getFile}?id=${res.data.id}`;
            break;
          default:
            break;
        }
      });
    },
    // 图片信息
    handleRemove(file, fileList) {
      // console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.ruleForm.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
};
</script>
<style scoped>
.from_main{
    margin-top:20px;
}
.from_main .el-input {
  width: 350px;
}
.videoadd {
  width: 100px;
  height: 100px;
  /*border:1px solid #ccc;*/
}
.imgbox {
  width: 180px;
  height: 150px;
  border: 1px dashed #dcdfe6;
}
.imgbox img {
  width: 100%;
  height: 100%;
}
.block {
  display: inline-block;
}
.postionImg {
  position: relative;
}
.postionAbsu {
  display: inline-block;
}
.postionImg1 {
  position: relative;
}
.postionAbsu1 {
  display: inline-block;
}
.postionImg2 {
  position: relative;
}
.postionAbsu2 {
  display: inline-block;
}
.postionImg3 {
  position: relative;
}
.postionAbsu3 {
  display: inline-block;
}
.upload-demo {
  display: inline-block;
}
</style>
<style>
.from .el-form-item__label {
  width: 140px !important;
}
.from p {
  width: 100%;
  color: #444;
  font-size: 14px;
  border-bottom: none !important;
  padding-bottom: 10px;
}
.informationadd .el-form-item__content {
  margin-left: 150px !important;
}
.informationadd .fotter_button{
  margin-left:0px !important;
}
</style>
